import pygame
import math
import random

class Player:
    """玩家角色类，管理玩家状态和行为"""
    def __init__(self, x, y, sprite_path, controls, screen_width, screen_height, opponent=None):
        """初始化玩家角色
        Args:
            x (int): 初始x坐标
            y (int): 初始y坐标
            sprite_path (str): 角色图片路径
            controls (dict): 控制键映射
            screen_width (int): 屏幕宽度
            screen_height (int): 屏幕高度
            opponent (Player): 对手玩家实例
        """
        self.sprite = pygame.image.load(sprite_path).convert_alpha()  # 加载角色图片
        self.sprite_path = sprite_path  # 存储图片路径
        self.damage_numbers = []  # 存储伤害数字
        self.score = 0  # 玩家分数
        self.score_timer = pygame.time.get_ticks() / 1000  # 分数计时器
        self.opponent = opponent  # 对手玩家
        self.rect = self.sprite.get_rect()  # 获取角色矩形区域
        self.x = x  # 当前x坐标
        self.y = y  # 当前y坐标
        self.controls = controls  # 控制键映射
        self.screen_width = screen_width  # 屏幕宽度
        self.screen_height = screen_height  # 屏幕高度
        self.health = 20  # 当前血量
        self.max_health = 20  # 最大血量
        self.speed = 5  # 移动速度
        self.respawn_timer = 0  # 复活计时器
        self.invincible = False  # 是否无敌
        self.invincible_timer = 0  # 无敌计时器
        self.flash_timer = 0  # 闪烁计时器
        self.reflect_damage = False  # 是否反射伤害
        self.reflect_timer = 0  # 反射伤害计时器
        self.attack_speed = 1.0  # 攻击速度
        self.attack_speed_timer = 0  # 攻击速度计时器
        self.respawn_points = [  # 复活点坐标
            (50, 50),
            (screen_width - 150, 50),
            (50, screen_height - 150),
            (screen_width - 150, screen_height - 150)
        ]

    def update_position(self, keys):
        """更新玩家位置
        Args:
            keys (dict): 当前按下的键
        """
        if keys[self.controls['up']]: self.y -= self.speed  # 上移
        if keys[self.controls['down']]: self.y += self.speed  # 下移
        if keys[self.controls['left']]: self.x -= self.speed  # 左移
        if keys[self.controls['right']]: self.x += self.speed  # 右移
         
        # 边界检查，防止角色移出屏幕
        self.x = max(0, min(self.x, self.screen_width - self.rect.width))
        self.y = max(0, min(self.y, self.screen_height - self.rect.height))
        self.rect.topleft = (self.x, self.y)

    def take_damage(self, amount):
        """处理玩家受到伤害
        Args:
            amount (int): 伤害值
        Returns:
            bool: 是否导致玩家死亡
        """
        if not self.invincible:  # 无敌状态下不受伤害
            self.health = max(0, self.health - amount)
            if self.health <= 0:
                self.respawn()  # 血量归零时触发复活
                return True
        return False
        
        # 添加伤害数字
        damage_number = {
            'value': amount,
            'x': self.x + self.rect.width // 2,
            'y': self.y,
            'color': (255, 0, 0) if not self.reflect_damage else (128, 0, 128),  # 红色或紫色
            'timer': 1.0  # 显示时间
        }
        self.damage_numbers.append(damage_number)

    def respawn(self):
        """处理玩家复活逻辑"""
        self.respawn_timer = pygame.time.get_ticks() / 1000 + 5  # 设置5秒复活计时
        self.invincible = True  # 进入无敌状态
        self.invincible_timer = pygame.time.get_ticks() / 1000 + 3  # 设置3秒无敌时间
        self.speed = 15  # 移动速度提升至3倍
        point = random.choice(self.respawn_points)  # 随机选择复活点
        self.x, self.y = point  # 设置新位置
        
        # 更新对手分数
        if self.opponent:
            self.opponent.score += 1
        
        # 更新最大血量
        self.max_health = 20 + self.score
        self.health = self.max_health  # 恢复满血

    def update_state(self, current_time):
        """更新玩家各种状态
        Args:
            current_time (float): 当前时间
        """
        if self.respawn_timer > 0 and current_time >= self.respawn_timer:
            self.respawn_timer = 0  # 清除复活计时
            self.speed = 5  # 恢复正常移动速度
            
        # 如果是丙，每分钟增加1分
        if '丙' in self.sprite_path and current_time - self.score_timer >= 60:
            self.score += 1
            self.score_timer = current_time
             
        if self.invincible and current_time >= self.invincible_timer:
            self.invincible = False  # 结束无敌状态
            self.speed = 5  # 恢复正常移动速度
             
        if self.reflect_damage and current_time >= self.reflect_timer:
            self.reflect_damage = False  # 结束伤害反射状态
             
        if self.attack_speed > 1.0 and current_time >= self.attack_speed_timer:
            self.attack_speed = 1.0  # 恢复正常攻击速度

    def draw(self, screen):
        """绘制玩家角色
        Args:
            screen (pygame.Surface): 游戏屏幕
        """
        if self.respawn_timer <= pygame.time.get_ticks() / 1000:  # 检查是否在复活状态
            if self.invincible and self.flash_timer < 0.5:  # 无敌状态下的闪烁效果
                screen.blit(self.sprite, (self.x, self.y))
            elif not self.invincible:  # 正常状态
                screen.blit(self.sprite, (self.x, self.y))
        
        # 绘制血量
        font = pygame.font.SysFont('Arial', 24, bold=True)
        health_text = f"HP: {self.health}/{self.max_health}"
        health_surface = font.render(health_text, True, (0, 255, 0))  # 绿色文字
        screen.blit(health_surface, (self.x, self.y - 50))  # 在角色上方显示血量
        
        # 绘制伤害数字
        self.draw_damage_numbers(screen)

    def update_damage_numbers(self, dt):
        """更新伤害数字状态
        Args:
            dt (float): 时间增量
        """
        for number in self.damage_numbers:
            number['y'] -= 50 * dt  # 数字向上移动
            number['timer'] -= dt  # 减少显示时间
        
        # 移除过期的伤害数字
        self.damage_numbers = [n for n in self.damage_numbers if n['timer'] > 0]

    def draw_damage_numbers(self, screen):
        """绘制伤害数字
        Args:
            screen (pygame.Surface): 游戏屏幕
        """
        font = pygame.font.SysFont('Arial', 24, bold=True)
        for number in self.damage_numbers:
            text_surface = font.render(str(number['value']), True, number['color'])
            screen.blit(text_surface, (number['x'], number['y']))